<template>
  <div class="g6_wrap">
    <div class="toolbox_wrap">
      <div class="title_wrap">
        <div class="title">
          工作流<span><i class="el-icon-arrow-down"></i></span>
        </div>
      </div>
      <div class="toolbox1">
        <input type="file" id="file2" hidden />
        <div
          class="toolbox_item"
          @click="onG6HandleFn(item)"
          v-for="item in toolboxList"
          :key="item.id"
        >
          <span :class="item.icon"></span>
          <span class="item111name">{{ item.name }}</span>
        </div>
      </div>
      <div :class="['toolbox2', currentG6Type !== 'edit' && 'watchClass']">
        <div
          class="toolbox_item"
          :title="item.name"
          v-for="item in addCanvasBoxList"
          :key="item.id"
          draggable
          @dragstart="handleDragstart"
          @dragend="
            (e) => {
              handleDragEnd(e, item);
            }
          "
        >
          <img :src="item.icon" alt="" srcset="" />
          <p>{{ item.name }}</p>
        </div>
      </div>
      <div
        :class="['draw_line', currentG6Type !== 'edit' && 'watchClass']"
        @click="isClickDarwLineFn"
      >
        <span
          class="draw_icon"
          :style="{ backgroundImage: `url(${drawLineobj.imgIcon})` }"
        ></span>
        <span>{{ isClickDrawLine ? "取消连线" : "开始连线" }}</span>
      </div>
      <el-button type="primary" class="backbtn" @click="onBackFn"
        >返回</el-button
      >
    </div>
    <div class="g6_main_wrapper">
      <div class="g6_tree">
        <div class="g6_tree_name">目录</div>
        <el-tree
          :data="g6TreeData"
          default-expand-all
          :props="g6TreeDefaultProps"
        ></el-tree>
      </div>
      <div class="g6_content">
        <div id="g6box" ref="g6box"></div>
      </div>
      <div class="g6_file_wrap">
        <div class="g6_file_box" v-if="isClickTypeItem === 'default'">
          <otherItem :commonG6FromObj="commonG6FromObj" />
        </div>
        <div class="g6_file_box" v-if="isClickTypeItem === '汇总'">
          <huizongItem :commonG6FromObj="commonG6FromObj" />
        </div>
        <div class="g6_file_box" v-if="isClickTypeItem === 'IF'">
          <ifItem :commonG6FromObj="commonG6FromObj" />
        </div>
        <div class="g6_file_box" v-if="isClickTypeItem === 'JAVA'">
          <javaItem :commonG6FromObj="commonG6FromObj" />
        </div>
        <div class="g6_file_box" v-if="isClickTypeItem === '筛选器'">
          <shaixuanqi :commonG6FromObj="commonG6FromObj" />
        </div>
        <div class="g6_file_box" v-if="isClickTypeItem === 'SQL'">
          <sqlItem :commonG6FromObj="commonG6FromObj" />
        </div>
        <div class="g6_file_box" v-if="isClickTypeItem === '源'">
          <yuanItem :commonG6FromObj="commonG6FromObj" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import G6 from "@antv/g6";
import otherItem from "./gzlComponents/otherItem.vue";
import huizongItem from "./gzlComponents/huizongItem.vue";
import ifItem from "./gzlComponents/ifItem.vue";
import javaItem from "./gzlComponents/javaItem.vue";
import shaixuanqi from "./gzlComponents/shaixuanqiItem.vue";
import sqlItem from "./gzlComponents/sqlItem.vue";
import yuanItem from "./gzlComponents/yuanItem.vue";
export default {
  props: {
    g6Data: {
      type: Object,
      default: () => {},
    },
    currentG6Type: {
      type: String,
      default: "",
    },
  },
  components: {
    otherItem,
    huizongItem,
    ifItem,
    javaItem,
    shaixuanqi,
    sqlItem,
    yuanItem,
  },
  data() {
    return {
      graph: null,
      offsetX: 0,
      offsetY: 0,
      toolboxList: [
        { id: 1, name: "导入", icon: "el-icon-upload2" },
        { id: 2, name: "导出", icon: "el-icon-download" },
        { id: 3, name: "拖动", icon: "el-icon-thumb" },
        { id: 4, name: "框选", icon: "el-icon-full-screen" },
        { id: 6, name: "发布", icon: "el-icon-position" },
      ],
      addCanvasBoxList: [
        {
          id: 1,
          name: "源",
          icon: require("@/assets/gzlgl/start.png"),
        },
        {
          id: 2,
          name: "目标",
          icon: require("@/assets/gzlgl/end.png"),
        },
        {
          id: 3,
          name: "开始",
          icon: require("@/assets/gzlgl/000.png"),
        },
        {
          id: 4,
          name: "筛选器",
          icon: require("@/assets/gzlgl/001.png"),
        },
        {
          id: 5,
          name: "汇总",
          icon: require("@/assets/gzlgl/002.png"),
        },
        {
          id: 6,
          name: "SQL",
          icon: require("@/assets/gzlgl/003.png"),
        },
        {
          id: 7,
          name: "JAVA",
          icon: require("@/assets/gzlgl/004.png"),
        },
        {
          id: 8,
          name: "IF",
          icon: require("@/assets/gzlgl/005.png"),
        },
        {
          id: 9,
          name: "JOIN",
          icon: require("@/assets/gzlgl/006.png"),
        },
        {
          id: 10,
          name: "存储过程",
          icon: require("@/assets/gzlgl/007.png"),
        },
        {
          id: 11,
          name: "数据流",
          icon: require("@/assets/gzlgl/008.png"),
        },
        {
          id: 12,
          name: "Script",
          icon: require("@/assets/gzlgl/009.png"),
        },
        {
          id: 13,
          name: "文件入库",
          icon: require("@/assets/gzlgl/010.png"),
        },
        {
          id: 14,
          name: "稽核",
          icon: require("@/assets/gzlgl/011.png"),
        },
        {
          id: 15,
          name: "Shell",
          icon: require("@/assets/gzlgl/012.png"),
        },
      ],
      g6TreeData: [
        {
          label: "一级 1",
          children: [
            {
              label: "二级 1-1",
              children: [
                {
                  label: "三级 1-1-1",
                },
                {
                  label: "三级 1-1-2",
                },
              ],
            },
          ],
        },
      ],
      drawLineobj: {
        id: 999,
        imgIcon: require("../../../../assets/gzlgl/000.png"),
      },
      g6TreeDefaultProps: {
        children: "children",
        label: "label",
      },
      commonG6FromObj: {
        isDailli: false,
        type: "",
        caozuo: "",
        lujing: "",
        canshu: "",
        beizhu: "",
        desc: "",
      },
      firstNodeItem: null,
      isClickDrawLine: false,
      isClickTypeItem: "default",
      clickNodeInfo: [
        {
          id: "源",
          fromObj: {
            type: "数据库",
            name: "数据库00A",
            IP: "192.168.100.03",
            duankou: "9999",
            userName: "哈哈哈",
            password: "123456",
            dataType: "mySQL",
            url: "https://openlayers.org/en/latest/examples/index.html",
            xieyi: "客户端",
            jiekou: "getAllItemSearch",
            actType: "网页浏览",
          },
        },
        {
          id: "IF",
          fromObj: {
            name: "IF啊哈哈",
            tableData: [
              { id: 1, biaodashi: "正则表达式", afterNode: "Join-node" },
              { id: 2, biaodashi: "cos表达式", afterNode: "Shell-node" },
              { id: 3, biaodashi: "ABS表达式", afterNode: "Java-node" },
            ],
          },
        },
        {
          id: "JAVA",
          fromObj: {
            name: "java脚本",
            type: "自执行脚本",
            jiaobenContent: "JAVA自执行啊哈哈哈",
            flieURL: "https://element.eleme.cn/#/zh-CN/component/table",
            beizhu: "JAVA备注啊啊哈哈哈阿杀时间",
          },
        },
        {
          id: "SQL",
          fromObj: {
            name: "我的数据库",
            tableData: [
              {
                id: 1,
                sourceUrl: "adsixg",
                tableName: "ngixib",
                yingsheName: "sajg映射",
              },
              {
                id: 2,
                sourceUrl: "ooibd",
                tableName: "䦹萨迪去",
                yingsheName: "巩固g映射",
              },
            ],
            jiaobenContent: "我是数据库的脚本内容撒娇和哥哥吧v",
            isRefech: true, //是否可以重试
            isBingfa: false, //并发控制
          },
        },
        {
          id: "汇总",
          fromObj: {
            name: "汇总啊啊啊啊哈",
            otherName: "汇总曾3",
            jiaobenContent: "汇总脚本内容事件啊很过分",
            tableData: [
              { id: 1, name: "字段001", biaodashi: "shag表达式" },
              { id: 2, name: "字段002", biaodashi: "bvbb表达式" },
              { id: 3, name: "字段005", biaodashi: "txch表达式" },
              { id: 4, name: "字段007", biaodashi: "ovht表达式" },
            ],
          },
        },
        {
          id: "筛选器",
          fromObj: {
            name: "筛选器AAi",
            otherName: "曾勇筛选去去去",
            tiaojian: "ng筛选",
            jiaobenContent: "筛选器阿瑟的环境不更改成功内容111",
            tableData: [
              { id: 1, name: "筛选你我" },
              { id: 2, name: "筛选sql" },
              { id: 3, name: "筛选jjava" },
            ],
          },
        },
        {
          id: "default",
          fromObj: {
            isDailli: false,
            type: "代理资源",
            caozuo: "手动运行",
            lujing:
              "https://blog.csdn.net/weixin_41825921/article/details/103992137",
            canshu: "test-mock",
            beizhu: "test-mocktest-mocktest-mocktest-mocktest-mock",
            desc: "test-mocktest-mocktest-mock",
          },
        },
      ],
      afterItemEv: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initNewG6Fn();
    });
  },
  methods: {
    // g6初始化并挂载方法
    initNewG6Fn() {
      let that = this;
      // 自定义连线
      G6.registerBehavior("click-add-edge", {
        // 设定该自定义行为需要监听的事件及其响应函数
        getEvents() {
          return {
            "node:click": "onClick",
            mousemove: "onMousemove",
            "edge:click": "onEdgeClick",
          };
        },
        onClick(ev) {
          const node = ev.item;
          if (!this.firstNodeItem) {
            this.firstNodeItem = ev.item._cfg.id;
          }
          // 鼠标当前点击的节点的位置
          const point = { x: ev.x, y: ev.y };
          const model = node.getModel();
          if (this.addingEdge && this.edge) {
            if (this.firstNodeItem != node._cfg.id) {
              this.graph.updateItem(this.edge, {
                target: model.id,
              });
            } else {
              this.graph.removeItem(this.edge);
            }
            this.firstNodeItem = null;
            this.edge = null;
            this.addingEdge = false;
          } else {
            // 在图上新增一条边，结束点是鼠标当前点击的节点的位置
            this.edge = this.graph.addItem("edge", {
              source: model.id,
              target: point,
            });
            this.addingEdge = true;
          }
        },
        onMousemove(ev) {
          // 鼠标的当前位置
          const point = { x: ev.x, y: ev.y };
          if (this.addingEdge && this.edge) {
            // 更新边的结束点位置为当前鼠标位置
            this.graph.updateItem(this.edge, {
              target: point,
            });
          }
        },
        onEdgeClick(ev) {
          const currentEdge = ev.item;
          this.firstNodeItem = null;
          // 拖拽过程中，点击会点击到新增的边上
          if (this.addingEdge && this.edge == currentEdge) {
            this.graph.removeItem(this.edge);
            this.edge = null;
            this.addingEdge = false;
          }
        },
      });
      // 自定义详情
      G6.registerBehavior("click-watch-info", {
        getEvents() {
          return {
            "node:click": "onNodeClick",
          };
        },
        onNodeClick(ev) {
          const { item } = ev;
          if (that.afterItemEv) {
            that.graph.clearItemStates(that.afterItemEv, "selected");
          }
          that.afterItemEv = item;
          if (!that.isClickDrawLine) {
            const itemModel = ev.item._cfg.model;
            let type = "";
            let commonObj = {};
            let clickItem = that.clickNodeInfo.filter((item) => {
              return item.id === itemModel.label;
            });
            if (clickItem.length) {
              type = itemModel.label;
              commonObj = clickItem[0].fromObj;
            } else {
              type = "default";
              commonObj =
                that.clickNodeInfo[that.clickNodeInfo.length - 1].fromObj;
            }
            that.isClickTypeItem = type;
            that.commonG6FromObj = commonObj;

            that.graph.setItemState(item, "selected", true);
          }
        },
      });
      const width = document.getElementById("g6box").clientWidth;
      const height = document.getElementById("g6box").offsetHeight;
      let typeMode = [];
      if (this.currentG6Type === "watch") {
        typeMode = ["drag-canvas", "zoom-canvas"];
      } else if (this.currentG6Type === "edit") {
        typeMode = [
          "zoom-canvas",
          "drag-node",
          "click-watch-info",
          { type: "brush-select", includeEdges: false },
        ];
      }
      this.graph = new G6.Graph({
        container: "g6box",
        width,
        height,
        modes: {
          // 允许拖拽画布、缩放画布、拖拽节点、选中节点、新增连线
          default: typeMode,
        },
        layout: {
          type: "dagre",
          rankdir: "LR", // 可选，默认为图的中心
          align: "DL", // 可选
          nodesep: 20, // 可选
          ranksep: 50, // 可选
          controlPoints: true, // 可选
        },
        defaultNode: {
          type: "image",
          size: [30, 35],
          style: {
            cursor: "pointer",
          },
          labelCfg: {
            position: "bottom",
            offset: 8,
            style: {
              fill: "#0089F4",
              fontSize: 12,
            },
          },
        },
        defaultEdge: {
          style: {
            stroke: "#0083fc",
            lineWidth: 0.8,
            endArrow: {
              path: G6.Arrow.triangle(),
              fill: "#0089F4",
            },
          },
        },
        nodeStateStyles: {
          selected: {
            shadowOffsetX: 3,
            shadowOffsetY: 3,
            shadowColor: "#00F",
            shadowBlur: 5,
          },
        },
      });
      this.graph.data(this.g6Data);
      this.graph.render();
    },
    // 添加相对应的元素
    addItemNodeFn(item) {
      if (this.currentG6Type !== "edit") {
        this.$message({
          message: "当前状态不可编辑~",
          type: "warning",
        });
        return;
      }
      let id = "node" + Math.random();
      let label = item.name;
      let img = item.icon;
      this.graph.addItem("node", {
        id,
        label,
        img,
      });
      this.graph.layout();
    },
    handleDragstart(e) {
      if (this.currentG6Type === "edit") {
        this.offsetX = e.offsetX;
        this.offsetY = e.offsetY;
      }
    },
    handleDragEnd(e, item) {
      if (this.currentG6Type === "edit") {
        let canvas = this.$refs.g6box.getElementsByTagName("canvas")[0];
        let ctx = canvas.getContext("2d");
        let jiange = canvas.getBoundingClientRect();
        ctx.rect(0, 0, canvas.width, canvas.height);
        if (
          ctx.isPointInPath(e.clientX - jiange.left, e.clientY - jiange.top)
        ) {
          var code = "";
          for (var i = 0; i < 2; i++) {
            var radom = Math.floor(Math.random() * 10);
            code += radom;
          }
          console.log(e.x, e.y);
          // 将屏幕/页面坐标转换为渲染坐标
          const xy = this.graph.getPointByClient(e.x, e.y);
          let id = "node" + Math.random();
          let label = item.name;
          console.log();

          let img = item.icon;
          let item1 = {
            id,
            label,
            img,
            x: xy.x,
            y: xy.y,
            offsetX: this.offsetX,
            offsetY: this.offsetY,
          };
          if (label === "开始") {
            item1.size = 30;
          }
          this.graph.addItem("node", item1);
          this.graph.fitView = true;
        }
      }
    },
    // 返回
    onBackFn() {
      this.$emit("isShowG6DialogFn", false);
    },
    onG6HandleFn(item) {
      if (item.name === "导出") {
        this.onSaveCanvasToPicFn();
      } else if (item.name === "导入") {
        console.log(1111);
        var file2 = document.getElementById("file2");
        file2.click();
        // this.onImportData();
      } else if (item.name === "发布") {
        this.onReleaseFn();
      } else if (item.name === "框选") {
        if (this.currentG6Type !== "edit") {
          this.$message({
            message: "当前状态不可使用该功能",
            type: "warning",
          });
          return;
        }
        this.$message({
          message: "按住shift激活框选功能",
          type: "success",
        });
      }
    },
    // 导入数据
    onImportData() {
      if (this.currentG6Type !== "edit") {
        this.$message({
          message: "当前状态不可导入数据",
          type: "warning",
        });
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "导入数据中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
        this.$message({
          message: "导入成功~",
          type: "success",
        });
        let itemArr = [
          {
            id: 1,
            name: "导入数据001",
            icon: require("../../../../assets/logo.png"),
          },
          {
            id: 2,
            name: "导入数据002",
            icon: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdesk-fd.zol-img.com.cn%2Ft_s960x600c5%2Fg2%2FM00%2F00%2F0B%2FChMlWl6yKqyILFoCACn-5rom2uIAAO4DgEODxAAKf7-298.jpg&refer=http%3A%2F%2Fdesk-fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648007152&t=1a1fd69f756aed9a3b1bf6c23eaeb112",
          },
          {
            id: 3,
            name: "导入数据003",
            icon: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F0F420110430%2F200F4110430-6-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648007152&t=2239a831ef5bd42b2c358921403b80bf",
          },
        ];
        itemArr.forEach((item) => {
          this.addItemNodeFn(item);
        });
      }, 3000);
    },
    // 导出图片
    onSaveCanvasToPicFn() {
      this.graph.downloadFullImage("g6图片", "image/jpeg", {
        backgroundColor: "#fff",
      });
    },
    // 发布
    onReleaseFn() {
      const loading = this.$loading({
        lock: true,
        text: "发布中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
        this.$message({
          message: "发布成功~",
          type: "success",
        });
        this.onBackFn();
      }, 3000);
    },
    // 切换模式
    isChangeModeFn(type) {
      if (type === "watch") {
        this.graph.setMode();
      } else if (type === "edit") {
        this.graph.setMode("edit");
      }
    },
    // 是否开启连线功能
    isClickDarwLineFn() {
      if (this.currentG6Type === "edit") {
        this.isClickDrawLine = !this.isClickDrawLine;
        if (this.isClickDrawLine) {
          this.graph.addBehaviors("click-add-edge", "default");
        } else {
          this.graph.removeBehaviors("click-add-edge", "default");
        }
      } else {
        this.$message({
          message: "该模式下禁止编辑!",
          type: "warning",
        });
      }
    },
  },
};
</script>
<style lang="less" scoped>
.g6_wrap {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  .toolbox_wrap {
    width: 100%;
    height: 60px;
    flex: 0 0 60px;
    display: flex;
    align-items: center;
    position: relative;
    box-sizing: border-box;
    padding: 0 20px;
    background-color: #e7f0fb;
    .title_wrap {
      display: flex;
      align-items: center;
      .title {
        font-size: 18px;
        color: #000;
      }
      .icon {
        width: 20px;
        height: 20px;
        background-color: #f00;
        margin-left: 12px;
      }
    }
    .toolbox1 {
      display: flex;
      align-items: center;
      margin-left: 35px;
      .toolbox_item {
        height: 50px;
        display: flex;
        font-size: 25px;
        flex-direction: column;
        align-items: center;
        margin-left: 15px;
        cursor: pointer;
        &:nth-child(3),
        &:nth-child(4) {
          color: #aaa;
          cursor: default;
        }
        .item111name {
          font-size: 12px;
          margin-top: 5px;
        }
      }
    }
    .toolbox2 {
      display: flex;
      align-items: center;
      margin-left: 35px;
      &.watchClass {
        .toolbox_item {
          -webkit-filter: grayscale(1); /* Webkit */
          filter: gray; /* IE6-9 */
          filter: grayscale(1); /* W3C */
          cursor: not-allowed;
        }
      }
      .toolbox_item {
        height: 50px;
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        margin-left: 14px;
        display: flex;
        flex-direction: column;
        align-items: center;
        &:first-child {
          margin-left: 0px;
        }
        img {
          height: 25px;
        }
        p {
          font-size: 12px;
          margin: 5px 0;
        }
      }
    }
    .draw_line {
      display: flex;
      height: 50px;
      flex-direction: column;
      align-items: center;
      font-size: 12px;
      margin-left: 15px;
      cursor: pointer;
      &.watchClass {
        -webkit-filter: grayscale(1); /* Webkit */
        filter: gray; /* IE6-9 */
        filter: grayscale(1); /* W3C */
        cursor: not-allowed;
      }
      .draw_icon {
        width: 25px;
        height: 25px;
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        margin-bottom: 5px;
      }
    }
    .backbtn {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      cursor: pointer;
    }
  }
  .g6_main_wrapper {
    width: 100%;
    height: 940px;
    display: flex;
    .g6_tree {
      flex: 0 0 200px;
      height: 100%;
      box-sizing: border-box;
      padding: 20px;
    }
    .g6_content {
      flex: 1 1 100%;
      height: 100%;
      box-sizing: border-box;
      border-left: 1px solid #ccc;
      border-right: 1px solid #ccc;
      #g6box {
        width: 100%;
        height: 100%;
      }
    }
    .g6_file_wrap {
      flex: 0 0 600px;
      box-sizing: border-box;
      padding: 20px 40px;
      height: 100%;
    }
  }
}
</style>
